import logging

import requests
import simplejson as json
import numpy as np
import os.path

import time
from bottle import run, request, Bottle, response
from expiringdict import ExpiringDict

import sys


app = Bottle()


def isValidIp(ip):
    return ip == None or ip == ''


def assembeToResult(respose, ip):
    result = {"code": 0,
              "data":
                  {
                      "ip": "",  # 58.240.254.154
                      "country": "",  # 中国
                      "area": "",
                      "region": "",  # 江苏
                      "city": "",  # 南京
                      "county": "",  # XX
                      "isp": "",  # 联通
                      "country_id": "",  # CN
                      "area_id": "",
                      "region_id": "",  # 320000
                      "city_id": "",  # 320100
                      "county_id": "",  # xx
                      "isp_id": ""  # 100026
                  }
              }
    response_data = json.loads(respose)['data']
    result['data']['ip'] = response_data['ip']
    result['data']['country'] = response_data['country']
    result['data']['region'] = response_data['region']
    result['data']['city'] = response_data['city']
    result['data']['county'] = response_data['county']
    # result['data']['county'] = '中国'
    result['data']['isp'] = response_data['isp']
    result['data']['country_id'] = response_data['country_id']
    result['data']['area_id'] = response_data['area_id']
    result['data']['region_id'] = response_data['region_id']
    result['data']['city_id'] = response_data['city_id']
    result['data']['county_id'] = response_data['county_id']
    result['data']['isp_id'] = response_data['isp_id']

    return result
    # return respose

def getIpInfo(ip):
    if ip in data_ip:
        logging.info("ip数据库 命中 ip=%s", ip)
        return json.dumps(data_ip[ip])
    logging.info("ip数据库 没命中 ip=%s", ip)

    r = requests.get("http://ip.taobao.com/service/getIpInfo.php?", {'ip': ip})
    result = assembeToResult(r.content.decode('UTF-8'), ip)

    data_ip[ip] = result
    # persistence to file
    logging.info("ip数据库 保存 ip=%s", ip)
    np.save(data_file_path, data_ip)

    return json.dumps(result,ensure_ascii=False,separators=(',', ':'))


@app.get("/ip")
def postRequest():
    response.content_type = 'text/html; charset=UTF-8'

    ip = request.query.ip
    if isValidIp(ip):
        return json.dumps({"code": 1, "data": ""})
    else:
        result_from_cache = cache.get(ip)
        if result_from_cache == None:
            logging.info("缓存没命中 ip=%s", ip)
            result = getIpInfo(ip)
            cache[ip] = result
            return result;
        else:
            logging.info("缓存命中 ip=%s", ip)
            return result_from_cache

# ip数据库文件
data_ip = {}
data_file_path = "data/ip_data.npy"

# cache保存个数为400，cache存活时间为600s
cache = ExpiringDict(max_len=400, max_age_seconds=600)

time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
log_file = "./log/logger-" + str(time_now) + ".log"
logging.basicConfig(format='%(asctime)-15s %(message)s', handlers=[logging.FileHandler(log_file, 'w', 'utf-8'),logging.StreamHandler()],
                    level=logging.INFO)

if __name__ == "__main__":
    args=sys.argv
    if os.path.isfile(data_file_path):
        data_ip = np.load('ip_data.npy').item()
    run(app, host='0.0.0.0', port=args[1])
